from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import UserProfile, Record

UserModel = get_user_model()


class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Record
        fields = ('id', 'display')


class GetUserAllowSerializer(serializers.ModelSerializer):
    sex = serializers.ChoiceField(choices=((1, '女'), (2, '男')))

    class Meta:
        model = UserProfile
        fields = ('id', 'name', 'username', 'phoneNumber', 'dateOfBirth', 'sex', 'age', 'discount', 'preDeposit', 'totalConsumption',
                    'integral', 'occupation', 'address', 'createdAt')


class PostUserSuperSerializer(serializers.ModelSerializer):
    sex = serializers.IntegerField()
    dateOfBirth = serializers.DateField()
    # password = serializers.HiddenField(required=False, default='88888888')

    class Meta:
        model = UserProfile
        fields = ('username', 'name', 'discount', 'sex', 'dateOfBirth', 'phoneNumber', 'address', 'records')

    def create(self, validated_data):
        username = validated_data['username']
        del validated_data['username']

        return UserModel.objects.create_user(username=username, email='', password='88888888', **validated_data)

    # def update(self, instance, validated_data):
    #     instance.discount = validated_data['discount']
    #     return instance


class GetUserSuperSerializer(serializers.ModelSerializer):
    sex = serializers.IntegerField()

    records = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = UserProfile
        fields = ('id', 'name', 'username', 'phoneNumber', 'dateOfBirth', 'sex', 'age', 'discount', 'preDeposit', 'totalConsumption',
                    'integral', 'occupation', 'address', 'createdAt', 'records')


class GetUserInfoSerializer(serializers.ModelSerializer):

    avatar = serializers.CharField(max_length=256, default='http://up.qqjia.com/z/26/tu32790_17.jpg')
    roles = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        fields = ('name', 'avatar', 'roles')

    def get_roles(self, obj):
        if obj.is_superuser:
            return ['admin']
        else:
            ret_permissions = [name for name in obj.get_all_permissions()]
            # ret_permissions = ret_permissions.extend([name for name in obj..values()])
            return ret_permissions


class ChangePassSerializer(serializers.Serializer):
    old_pass = serializers.CharField()
    new_pass = serializers.CharField()
    new_pass1 = serializers.CharField()


class ScanUserSerializer(serializers.Serializer):
    filter_upn = serializers.CharField(required=True)


class ScanUserRetSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('id', 'name', 'username', 'phoneNumber', 'discount')
